<template>
  <div class="screen-adapter" :style="style">
    <slot />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
let style = ref({
  width: "1920px",
  height: "1080px",
  transform: "scale(1) translate(-50%, -50%)",
});
onMounted(() => {
  getScale();
  onresize();
  window.addEventListener("resize", onresize);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", onresize);
});
const getScale = () => {
  const w = window.innerWidth / 1920;
  const h = window.innerHeight / 1080;
  return w < h ? w : h;
};
const debounce = (fn: any, t: number) => {
  const delay = t || 200;
  let timer: any;
  return function (this: any) {
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    const context = this;
    timer = setTimeout(() => {
      timer = null;
      fn.apply(context, args);
    }, delay);
  };
};

const setScale = () => {
  style.value.transform = "scale(" + getScale() + ") translate(-50%, -50%)";
};
const onresize = debounce(() => setScale(), 100);
</script>

<style scoped>
.screen-adapter {
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.1s;
}
</style>
